package com.shi.desktop.indexer;

import java.io.IOException;
import java.io.InputStream;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class WordDocHandler implements DocumentHandler {

	public Document getDocument(InputStream is) throws DocumentHandlerException {
		
		String bodyText = null;
		String author = null;
		String title = null;
		String subject = null;
		String keywords = null;
		
		try {
			WordExtractor extractor = new WordExtractor(is);
			bodyText = extractor.getText();
			SummaryInformation si = extractor.getSummaryInformation();
			author = si.getAuthor();
			title = si.getTitle();
			subject = si.getSubject();
			keywords = si.getKeywords();
		} catch (IOException e) {
			throw new DocumentHandlerException("Error: Cannot load file.", e);
		} catch (IllegalArgumentException e) {
			throw new DocumentHandlerException("Error: Cannot load file.", e);
		}
		
		Document doc = new Document();
		if (bodyText != null) {
			doc.add(new Field("content", bodyText, Field.Store.NO,
					Field.Index.ANALYZED));
		}
		if ((author != null) && !author.equals("")) {
			doc.add(new Field("author", author, Field.Store.YES,
					Field.Index.NOT_ANALYZED));
		}
		if ((title != null) && !title.equals("")) {
			doc.add(new Field("title", title, Field.Store.YES,
					Field.Index.ANALYZED));
		}
		if ((keywords != null) && !keywords.equals("")) {
			doc.add(new Field("keywords", keywords, Field.Store.YES,
					Field.Index.NOT_ANALYZED));
		}
		if ((subject != null) && !subject.equals("")) {
			doc.add(new Field("subject", subject, Field.Store.YES,
					Field.Index.ANALYZED));
		}
		return doc;
	}
}
